#!/usr/bin/env perl

use warnings;

# Given a database connection key, this script simply exec's "psql" with the
# appropriate args.

use strict;

use FindBin;
use lib "$FindBin::Bin/../lib";

use strict;
use DBDefs;
use Getopt::Long;

use aliased 'MusicBrainz::Server::DatabaseConnectionFactory' => 'Databases';

my $system = 0;
my $help = 0;

GetOptions(
    'system'    => \$system,
    'help'      => \$help,
) or exit 2;

my $key = shift // 'READWRITE';

die <<EOF if $help;
Usage: $0 [options] [database]

Arguments:

    database    The name of the database connection definition to use,
                as registered in DBDefs.
                (default: READWRITE)

Options:

    --system    Partly overwrite the database connection definition
                with the properties (usually username/password)
                of the database connection definition SYSTEM.
                It allows connecting to any database as superuser.
             
Environment:

    PGPASSWORD  If set, it is used as password to connect to the database.
EOF

my $db = Databases->get($key) or die "No such database '$key'\n";

if ($system) {
    $db = Databases->get('SYSTEM_' . $key);
}

$ENV{'PGPASSWORD'} = $db->password;

exec 'psql', $db->shell_args, @ARGV;

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2002 Robert Kaye

This file is part of MusicBrainz, the open internet music database,
and is licensed under the GPL version 2, or (at your option) any
later version: http://www.gnu.org/licenses/gpl-2.0.txt

=cut
